/*
 * SFTPMessage.h
 *
 *  Created on: Mar 14, 2011
 *      Author: sms103
 */

#ifndef SFTPMESSAGE_H_
#define SFTPMESSAGE_H_

#include <sys/types.h>
#include <stdint.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <string>
#include <assert.h>

#include "SFTPTransportSocket.h"
#include "../shared/ParamParser.h"

using namespace std;

#define MSG_TYPE_TEST 0
#define MSG_TYPE_CLOSE 1
#define MSG_TYPE_CTRL_INIT 2
#define MSG_TYPE_DATA_INIT 3

#define MSG_TYPE_TRANSF_INIT 4
#define MSG_TYPE_TRANSF_COMPLETE 5
#define MSG_TYPE_TRANSF_DATA 6


//control message to begin a file "put"-transfer from client to server
//full path name is sent as data part of this message
#define MSG_TYPE_PUT 7

//control message to begin a file "get"-transfer from server to client
//full path name is sent as data part of this message
#define MSG_TYPE_GET 8

//control message to request a list of directory contents from the server
//full directory name is sent as data part of this message
#define MSG_TYPE_LIS 9

//indicates failure of some current operation
#define MSG_TYPE_FAIL 10


struct sftp_message_header{
	uint8_t type;
	uint8_t flags;
	uint32_t attr;
	uint32_t dataLength;
};

class SFTPMessage {
public:
	SFTPMessage(uint32_t transportMSS);
	virtual ~SFTPMessage();

	//adds len bytes from buf to the end of this messages data buffer
	//returns bytes added--if the size exceeds MAX_MSG_SIZE less than len
	//bytes could be added
	size_t addData(void *buf, size_t len);

	//clears data of this message. adding after this will
	//start from the beginning of data buffer.
	void clearData();

	/* Sets up to len bytes from buf as the data of this message.
	 * returns number of bytes used. Only less than len if len
	 * is greater than max amount of data allowed in a msg. copies
	 * from buf--buf needs to be freed by caller if they wish.
	 */
	size_t setData(void *buf, size_t len);

	//Sets up to s.size() bytes from s as the data of this message.
	size_t setStrData(string s);

	//
	string& getStrData();

	//sets type field in header to t
	void setType(uint8_t t);

	//sets the attr field in header to attr
	void setAttr(uint32_t attr);

	void * mbuf();
	void * getData();
	sftp_message_header * getHeader();
	void toNetByteOrder();
	void toHostByteOrder();

	uint32_t getMaxMessageSize();


private:
	ParamParser *paramParser;
	void *messageBuf;
	sftp_message_header *hdr;
	void *data;
	uint32_t currDataBufLen;//total allocated size of buffer

	uint32_t maxMessageSize;


	void setParams(uint32_t transportMSS);
};

#endif /* SFTPMESSAGE_H_ */
